<?php

// phpMyRealty 3
//
// File Name: calculator.php
// File Location : ./
//
// Copyright (c)2009 phpMyRealty.com
//
// e-mail: support@phpMyRealty.com

// Include configuration file and general functions
define('PMR', 'true');

$page = 'calculator';

include ( './config.php' );
include ( PATH . '/defaults.php' );

// ----------------------------------------------------------------------
// Mortgage Calculator

error_reporting  ( 'E_NONE' );

// Title tag content
$title = $conf['website_name_short'] . ' - ' . $lang['Mortgage_Calculator'];

// Template header
include ( PATH . '/templates/' . $cookie_template . '/header.php' );

// Output the Find Property form
echo table_header ( $lang['Mortgage_Calculator'] );

    /*
        PHP Mortgage Calculator
        version: 1.1
        last update: Jan 1, 2003
        ----------------------------------------------------
        The PHP Mortgage Calculator tries to figure out a home 
        owners mortgage payments, and the breakdown of each monthly
        payment.
        
        The calculator accepts:
            Price (cost of home in US Dollars)
            Percentage of Down Payment
            Length of Mortgage
            Annual Interest Rate
        
        Based on the four items that the user enters, we can figure
        out the down payment (in US Dollars), the ammount that the 
        buyer needs to finance, and the monthly finance payment. 
        The calculator can also break down the monthly payments 
        so we know how much goes towards the mortgage's interest, 
        the mortgage's principal, the loan's Private Mortgage Insurance 
        (if less that 20% was used as a down payment), and an rough 
        estimate of the property's residential tax
        
        [ See below for LICENSE ]
    */
    
    /* --------------------------------------------------- *
     * Set Form DEFAULT values
     * --------------------------------------------------- */
    $default_sale_price              = "100000";
    $default_annual_interest_percent = 6.0;
    $default_year_term               = 30;
    $default_down_percent            = 10;
    $default_show_progress           = TRUE;
    /* --------------------------------------------------- */
    


    /* --------------------------------------------------- *
     * Initialize Variables
     * --------------------------------------------------- */
    $sale_price                      = 0;
    $annual_interest_percent         = 0;
    $year_term                       = 0;
    $down_percent                    = 0;
    $this_year_interest_paid         = 0;
    $this_year_principal_paid        = 0;
    $form_complete                   = false;
    $show_progress                   = false;
    $monthly_payment                 = false;
    $show_progress                   = false;
    $error                           = false;
    /* --------------------------------------------------- */


    /* --------------------------------------------------- *
     * Set the USER INPUT values
     * --------------------------------------------------- */
    if (isset($_REQUEST['form_complete'])) {
        $sale_price                      = $_REQUEST['sale_price'];
        $annual_interest_percent         = $_REQUEST['annual_interest_percent'];
        $year_term                       = $_REQUEST['year_term'];
        $down_percent                    = $_REQUEST['down_percent'];
        $show_progress                   = (isset($_REQUEST['show_progress'])) ? $_REQUEST['show_progress'] : false;
        $form_complete                   = $_REQUEST['form_complete'];
    }
    /* --------------------------------------------------- */
  
    // This function does the actual mortgage calculations
    // by plotting a PVIFA (Present Value Interest Factor of Annuity)
    // table...
    function get_interest_factor($year_term, $monthly_interest_rate) {
        global $base_rate;
        
        $factor      = 0;
        $base_rate   = 1 + $monthly_interest_rate;
        $denominator = $base_rate;
        for ($i=0; $i < ($year_term * 12); $i++) {
            $factor += (1 / $denominator);
            $denominator *= $base_rate;
        }
        return $factor;
    }        
    /* --------------------------------------------------- */

    // If the form is complete, we'll start the math
    if ($form_complete) {
        // We'll set all the numeric values to JUST
        // numbers - this will delete any dollars signs,
        // commas, spaces, and letters, without invalidating
        // the value of the number
        $sale_price              = ereg_replace( "[^0-9.]", "", $sale_price);
        $annual_interest_percent = eregi_replace("[^0-9.]", "", $annual_interest_percent);
        $year_term               = eregi_replace("[^0-9.]", "", $year_term);
        $down_percent            = eregi_replace("[^0-9.]", "", $down_percent);
        
        if (((float) $year_term <= 0) || ((float) $sale_price <= 0) || ((float) $annual_interest_percent <= 0)) {
            echo $lang['Calculator_Error_No_Inputs'];
        }
        
        if (!$error) {
            $month_term              = $year_term * 12;
            $down_payment            = $sale_price * ($down_percent / 100);
            $annual_interest_rate    = $annual_interest_percent / 100;
            $monthly_interest_rate   = $annual_interest_rate / 12;
            $financing_price         = $sale_price - $down_payment;
            $monthly_factor          = get_interest_factor($year_term, $monthly_interest_rate);
            $monthly_payment         = $financing_price / $monthly_factor;
        }
    } else {
        if (!$sale_price)              { $sale_price              = $default_sale_price;              }
        if (!$annual_interest_percent) { $annual_interest_percent = $default_annual_interest_percent; }
        if (!$year_term)               { $year_term               = $default_year_term;               }
        if (!$down_percent)            { $down_percent            = $default_down_percent;            }
        if (!$show_progress)           { $show_progress           = $default_show_progress;           }
    }
    
    if ($error) {
        print("<font color=\"red\">" . $error . "</font><br /><br />\n");
        $form_complete   = false;
    }
?>

<form method="GET" name="information" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="form_complete" value="1">
<table cellpadding="7" cellspacing="0" border="0" width="100%">

    <tr valign="top" >
        <td width="50%" align="right"><?php echo $lang['Calculator_Sale_Price']; ?>:</td>
        <td width="50%"><input type="text" size="10" name="sale_price" value="<?php echo $sale_price; ?>"> <?php echo $lang['Calculator_Sale_Price_Example']; ?></td>
    </tr>
    <tr valign="top" >
        <td align="right"><?php echo $lang['Calculator_Percentage_Down']; ?>:</td>
        <td><input type="text" size="5" name="down_percent" value="<?php echo $down_percent; ?>"> <?php echo $lang['Calculator_Percentage_Down_Example']; ?></td>
    </tr>
    <tr valign="top" >
        <td align="right"><?php echo $lang['Calculator_Mortgage_Length']; ?>:</td>
        <td><input type="text" size="3" name="year_term" value="<?php echo $year_term; ?>"> <?php echo $lang['Calculator_Mortgage_Length_Example']; ?></td>
    </tr>
    <tr valign="top" >
        <td align="right"><?php echo $lang['Calculator_Interest_Rate']; ?>:</td>
        <td><input type="text" size="5" name="annual_interest_percent" value="<?php echo $annual_interest_percent; ?>"> <?php echo $lang['Calculator_Interest_Rate_Example']; ?></td>
    </tr>
    <tr valign="top" >
        <td align="right"><?php echo $lang['Calculator_Explain_Calculations']; ?>:</td>
        <td><input type="checkbox" name="show_progress" value="1" <?php if ($show_progress) { print("checked"); } ?>> <?php echo $lang['Calculator_Explain_Calculations_Example']; ?></td>
    </tr>
    <tr valign="top" >
        <td>&nbsp;</td>
        <td><input type="submit" class="submit" value="<?php echo $lang['Calculator_Calculate']; ?>"><br /></td>
    </tr>

<?php
    // If the form has already been calculated, the $down_payment
    // and $monthly_payment variables will be figured out, so we
    // can show them in this table
    if ($form_complete && $monthly_payment) {
?>
        <tr valign="top">
            <td align="center" colspan="2" bgcolor="#000000"><font color="#ffffff"><b><?php echo $lang['Calculator_Mortgage_Payment_Information']; ?></b></font></td>
        </tr>
        <tr valign="top" bgcolor="#eeeeee">
            <td align="right"><?php echo $lang['Calculator_Down_Payment']; ?>:</td>
            <td><b><?php echo $conf['currency'] . pmr_number_format($down_payment, 2); ?></b></td>
        </tr>
        <tr valign="top" bgcolor="#eeeeee">
            <td align="right"><?php echo $lang['Calculator_Amount_Financed']; ?>:</td>
            <td><b><?php echo $conf['currency'] . pmr_number_format($financing_price, 2); ?></b></td>
        </tr>
        <tr valign="top" bgcolor="#cccccc">
            <td align="right"><?php echo $lang['Calculator_Monthly_Payment']; ?>:</td>
            <td><b><?php echo $conf['currency'] . pmr_number_format($monthly_payment, 2); ?></b><br /><font><?php echo $lang['Calculator_Monthly_Payment_Example']; ?></font></td>
        </tr>
        <?php
            if ($down_percent < 20) {
                $pmi_per_month = 55 * ($financing_price / 100000);
        ?>
                <tr valign="top" bgcolor="#FFFFCC">
                    <td align="right">&nbsp;</td>
                    <td>
                        <br />
                        <?php echo $lang['Calculator_PMI_Notice']; ?> <?php echo $conf['currency'] . pmr_number_format($pmi_per_month, 2); ?>
                    </td>
                </tr>
                <tr valign="top" bgcolor="#FFFF99">
                    <td align="right"><?php echo $lang['Calculator_Monthly_Payment']; ?>:</td>
                    <td><b><?php echo $conf['currency'] . pmr_number_format(($monthly_payment + $pmi_per_month), 2); ?></b><br /><font><?php echo $lang['Calculator_Monthly_Payment_PMI_Example']; ?></td>
                </tr>
        <?php
            }
        ?>
        <tr valign="top" bgcolor="#CCCCFF">
            <td align="right">&nbsp;</td>
            <td>
                <br />
                <?php
                    $assessed_price          = ($sale_price * .85);
                    $residential_yearly_tax  = ($assessed_price / 1000) * 14;
                    $residential_monthly_tax = $residential_yearly_tax / 12;
                    
                    if ($pmi_per_month) {
                        $pmi_text = $lang['Calculator_PMI_And'];
                    }
                ?>
                <?php echo $lang['Calculator_Tax_Assumption']; ?> <?php echo $conf['currency'] . pmr_number_format($assessed_price, 2); ?>. <?php echo $lang['Calculator_Tax_Conclusion']; ?> <?php echo $conf['currency'] . pmr_number_format($residential_yearly_tax, 2); ?>
                <?php echo $lang['Calculator_Monthly_Payment_With_Taxes']; ?>: <?php echo $conf['currency'] . pmr_number_format($residential_monthly_tax, 2); ?>
            </td>
        </tr>
        <tr valign="top" bgcolor="#9999FF">
            <td align="right"><?php echo $lang['Calculator_Total_Monthly_Payment']; ?>:</td>
            <td><b><?php echo $conf['currency'] . pmr_number_format(($monthly_payment + $pmi_per_month + $residential_monthly_tax), 2); ?></b><br /><font>, <?php echo $lang['Calculator_Including_Tax']; ?>&nbsp;<?php echo $pmi_text; ?></font></td>
        </tr>
<?php    
    }
?>
</table>
</form>
<?php
    // This prints the calculation progress and 
    // the instructions of HOW everything is figured
    // out
    if ($form_complete && $show_progress) {
        $step = 1;
?>
        <br /><br />
        <table cellpadding="5" cellspacing="0" border="0" width="100%">
            <tr valign="top">
                <td><b><?php echo $step++; ?></b></td>
                <td>
                    <?php echo $lang['Calculator_Down_Payment_Explanation']; ?><br /><br />
                    <?php echo $conf['currency'] . pmr_number_format($down_payment, 2); ?> = R<?php echo pmr_number_format($sale_price, 2); ?> X (<?php echo $down_percent; ?> / 100)
                </td>
            </tr>
            <tr valign="top">
                <td><b><?php echo $step++; ?></b></td>
                <td>
                    <?php echo $lang['Calculator_Interest_Rate_Explanation']; ?><br /><br />
                    <?php echo $annual_interest_rate; ?> = <?php echo $annual_interest_percent; ?>% / 100
                </td>
            </tr>
            <tr valign="top" bgcolor="#cccccc">
                <td colspan="2">
                    <?php echo $lang['Calculator_Monthly_Rate_Formula_Explanation']; ?>
                </td>
            </tr>
            <tr valign="top">
                <td><b><?php echo $step++; ?></b></td>
                <td>
                    <?php echo $lang['Calculator_Monthly_Interest_Rate_Explanation']; ?><br /><br />
                    <?php echo $monthly_interest_rate; ?> = <?php echo $annual_interest_rate; ?> / 12
                </td>
            </tr>
            <tr valign="top">
                <td><b><?php echo $step++; ?></b></td>
                <td>
                    <?php echo $lang['Calculator_Monthly_Term_Explanation']; ?><br /><br />
                    <?php echo $month_term; ?> <?php echo $lang['Calculator_Months']; ?> = <?php echo $year_term; ?> <?php echo $lang['Calculator_Years']; ?> X 12
                </td>
            </tr>
            <tr valign="top">
                <td><b><?php echo $step++; ?></b></td>
                <td>
                    <?php echo $lang['Calculator_Monthly_Payment_Formula_Explanation']; ?><br />
                    <?php echo $lang['Calculator_Monthly_Payment']; ?> = <?php echo number_format($financing_price, "2", "", ""); ?> * (<?php echo number_format($monthly_interest_rate, "4", "", ""); ?> / (1 - ((1 + <?php echo number_format($monthly_interest_rate, "4", "", ""); ?>)<sup>-(<?php echo $month_term; ?>)</sup>)))
                    <br /><br />
                    <?php echo $lang['Calculator_Amortization_Explanation']; ?>
                </td>
            </tr>
        </table>
        <br />
<?php
        // Set some base variables
        $principal     = $financing_price;
        $current_month = 1;
        $current_year  = 1;
        // This basically, re-figures out the monthly payment, again.
        $power = -($month_term);
        $denom = pow((1 + $monthly_interest_rate), $power);
        $monthly_payment = $principal * ($monthly_interest_rate / (1 - $denom));
        
        print("<br /><br /><a name=\"amortization\"></a>" . $lang['Calculator_Amortization_Monthly_Payment'] . ": <b>" . $conf['currency'] . pmr_number_format($monthly_payment, 2) . "</b> " . $lang['Calculator_For'] . " " . $year_term . " " . $lang['Calculator_Years'] . "<br />\n");
        print("<table cellpadding=\"5\" cellspacing=\"0\" bgcolor=\"#eeeeee\" border=\"0\" width=\"100%\">\n");
        
        // This LEGEND will get reprinted every 12 months
        $legend  = "\t<tr valign=\"top\" bgcolor=\"#cccccc\">\n";
        $legend .= "\t\t<td align=\"right\"><b>" . $lang['Calculator_Month'] . "</b></td>\n";
        $legend .= "\t\t<td align=\"right\"><b>" . $lang['Calculator_Interest_Paid'] . "</b></td>\n";
        $legend .= "\t\t<td align=\"right\"><b>" . $lang['Calculator_Principal_Paid'] . "</b></td>\n";
        $legend .= "\t\t<td align=\"right\"><b>" . $lang['Calculator_Remaining_Balance'] . "</b></td>\n";
        $legend .= "\t</tr>\n";
        
        echo $legend;
                
        // Loop through and get the current month's payments for 
        // the length of the loan 
        while ($current_month <= $month_term) {        
            $interest_paid     = $principal * $monthly_interest_rate;
            $principal_paid    = $monthly_payment - $interest_paid;
            $remaining_balance = $principal - $principal_paid;
            
            $this_year_interest_paid  = $this_year_interest_paid + $interest_paid;
            $this_year_principal_paid = $this_year_principal_paid + $principal_paid;
            
            print("\t<tr valign=\"top\" bgcolor=\"#eeeeee\">\n");
            print("\t\t<td align=\"right\">" . $current_month . "</td>\n");
            print("\t\t<td align=\"right\">" . $conf['currency'] . pmr_number_format($interest_paid, 2) . "</td>\n");
            print("\t\t<td align=\"right\">" . $conf['currency'] . pmr_number_format($principal_paid, 2) . "</td>\n");
            print("\t\t<td align=\"right\">" . $conf['currency'] . pmr_number_format($remaining_balance, 2) . "</td>\n");
            print("\t</tr>\n");
    
            ($current_month % 12) ? $show_legend = FALSE : $show_legend = TRUE;
    
            if ($show_legend) {
                print("\t<tr valign=\"top\" bgcolor=\"#ffffcc\">\n");
                print("\t\t<td colspan=\"4\"><b>" . $lang['Calculator_Totals_For_Year'] . " " . $current_year . "</td>\n");
                print("\t</tr>\n");
                
                $total_spent_this_year = $this_year_interest_paid + $this_year_principal_paid;
                print("\t<tr valign=\"top\" bgcolor=\"#ffffcc\">\n");
                print("\t\t<td>&nbsp;</td>\n");
                print("\t\t<td colspan=\"3\">\n");
                print("\t\t\t" . $lang['Calculator_You_Will_Spend'] . " " . $conf['currency'] . pmr_number_format($total_spent_this_year, 2) . " " . $lang['Calculator_In_A_Year'] . " " . $current_year . "<br />\n");
                print("\t\t\t" . $conf['currency'] . pmr_number_format($this_year_interest_paid, 2) . " " . $lang['Calculator_Will_Go_Towards'] . " " . $lang['Calculator_Interest'] . "<br />\n");
                print("\t\t\t" . $conf['currency'] . pmr_number_format($this_year_principal_paid, 2) . " " . $lang['Calculator_Will_Go_Towards'] . " " . $lang['Calculator_Principal'] . "<br />\n");
                print("\t\t</td>\n");
                print("\t</tr>\n");
    
                print("\t<tr valign=\"top\" bgcolor=\"#ffffff\">\n");
                print("\t\t<td colspan=\"4\">&nbsp;<br /><br /></td>\n");
                print("\t</tr>\n");
                
                $current_year++;
                $this_year_interest_paid  = 0;
                $this_year_principal_paid = 0;
                
                if (($current_month + 6) < $month_term) {
                    echo $legend;
                }
            }
    
            $principal = $remaining_balance;
            $current_month++;
        }
        print("</table>\n");
    }
?>
<br />

<!-- END BODY -->

<?php

/*
    ///// mortgage_calculator.php /////
    Copyright (c) 2002 David Tufts <http://dave.imarc.net> 
    All rights reserved.
    
    Redistribution and use in source and binary forms, with or without 
    modification, are permitted provided that the following conditions 
    are met:
    
    *    Redistributions of source code must retain the above copyright 
     notice, this list of conditions and the following disclaimer.
    *    Redistributions in binary form must reproduce the above 
     copyright notice, this list of conditions and the following 
     disclaimer in the documentation and/or other materials 
     provided with the distribution.
    *    Neither the name of David Tufts nor the names of its 
     contributors may be used to endorse or promote products 
     derived from this software without specific prior 
     written permission.
    
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
    CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 
    BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
    TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
    ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
    OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
    POSSIBILITY OF SUCH DAMAGE.
*/

echo table_footer ();

// Template Footer
include ( PATH . '/templates/' . $cookie_template . '/footer.php' );

?>